@echo off
echo Installing Device Mode Monitor Service...

rem Check for administrator privileges
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo Error: Please run this script as administrator!
    pause
    exit /b 1
)

rem Get current directory for creating the service
set CURRENT_DIR=%~dp0
set EXECUTABLE="%CURRENT_DIR%DeviceModeMonitor.exe"
echo Service executable path: %EXECUTABLE%

rem Stop and remove existing service if it exists
echo Checking for existing service...
sc query DeviceModeMonitor >nul 2>&1
if %errorLevel% equ 0 (
    echo Found existing service, stopping and removing...
    sc stop DeviceModeMonitor >nul 2>&1
    timeout /t 3 >nul
    sc delete DeviceModeMonitor >nul 2>&1
    timeout /t 2 >nul
    echo Old service removed.
)

rem Create new service - with proper service type
echo Creating new service...
sc create DeviceModeMonitor binPath= %EXECUTABLE% type= own start= auto DisplayName= "Device Mode Monitor" error= normal obj= "LocalSystem"
if %errorLevel% neq 0 (
    echo Service creation failed! Error code: %errorLevel%
    echo Please check if service name conflicts or if the program has the correct service entry point.
    pause
    exit /b 1
)

rem Set service description
echo Setting service description...
sc description DeviceModeMonitor "Monitors connection status of specific devices and automatically switches between desktop and tablet modes."

rem Set additional service properties - auto startup and crash recovery
echo Configuring service properties...
reg add "HKLM\SYSTEM\CurrentControlSet\Services\DeviceModeMonitor" /v "DelayedAutostart" /t REG_DWORD /d 0 /f

rem Set service recovery options
echo Setting service recovery options...
sc failure DeviceModeMonitor reset= 86400 actions= restart/30000/restart/60000/restart/90000

rem Ensure the service has necessary permissions
echo Setting service permissions...
sc privs DeviceModeMonitor SeChangeNotifyPrivilege/SeCreateGlobalPrivilege/SeIncreaseWorkingSetPrivilege

rem Start the service
echo Starting service...
sc start DeviceModeMonitor
if %errorLevel% neq 0 (
    echo Warning: Service created but failed to start. Error code: %errorLevel%
    echo This could be normal the first time. Try manually starting the service:
    echo 1. Open services.msc
    echo 2. Find "Device Mode Monitor" service
    echo 3. Right-click and select "Start"
) else (
    echo Service installed and started successfully!
)

echo.
echo The service has been installed and set to start automatically after system reboot.
pause
